import { WebsitePartType } from '@/components/AppBox/types'
import { WidgetSizeType } from '@/Widgets/Widget/types'
import { appLocalStorage } from '@/utils/tools'
import { WidgetsPropsType, WidgetsType } from '@/Widgets'
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { isEmpty, isNil } from 'lodash'
import { SearchType } from '@/config/types'

const updateUserAppConfig = async (appConfig: any) => {
  appLocalStorage.setValue('appConfig', appConfig)
}

const page = {
  currentPage: 'home',
  pageList: [
    {
      label: '首页',
      key: 'home',
      icon: 'home',
    },
  ],
  boxs: {
    home: {
      "list": [
        {
          type: "website",
          typeProps: {
            title: "一网一匠",
            icon: "https://ywyj.cn/logo.png",
            harf: "https://www.ywyj.cn"
          }
        },

      ]
    }
  },
  part: {
    title: true
  },
}

const background = {
  currentImage: 'https://img.win3000.com/m00/cc/df/5b9661a69b7801391711ed40e04e581f.jpg',
  // currentImage: 'https://img.win3000.com/m00/5e/eb/c94df32a91f9a2a079f2d201d6741f1e.jpg',
  // currentImage: 'https://img.win3000.com/m00/55/60/5511c4b9a723a7954ffda87b080f264a.png',
  blur: 0,
}

const box = {
  radius: 12,
  size: 80,
  shadow: {
    h: 0,
    w: 0,
    blur: 6,
    spread: 0,
    show: 'hover', // hover always never
  }
}

type OtherType = {
  theme: 'dark' | 'light',
  appDrawer: {
    open: boolean
  },
  appDrawerBoxsList: {
    sizeType: WidgetSizeType,
    widgetType: WidgetsType,
    typeProps: WidgetsPropsType
  }[],
  /**
   * 极简模式
   */
  conciseMode: boolean,
  currentSearchEngines: SearchType
}


const other: OtherType = {
  // 主题样式
  theme: 'light',
  // 抽屉（工具配置）
  appDrawer: {
    open: true,
  },
  appDrawerBoxsList: [
    {
      sizeType: "2-2",
      typeProps: {},
      widgetType: "weather",
    },
    {
      sizeType: "2-2",
      typeProps: {},
      widgetType: "scanQRcode",
    },
  ],
  /**
   * 简洁模式
   */
  conciseMode: false,
  currentSearchEngines: {
    label: '百度',
    key: 'baidu',
    url: 'https://www.baidu.com/s?ie-utf8&word=',
    iconImage: 'searchIcons/images/baidu.png',
    iconSvg: 'searchIcons/svg/baidu.svg',
    tags: ['常用']
  }
}

/**
 * 系统设置
 */
const systemSettins = {
  /**
   * 在新标签页打开新网页
   */
  openWebsiteInNewTab: true,
  /**
   * 在新标签页打开搜索结果
   */
  openSearchResultInNewTab: true,
  /**
   * 隐藏图标名称
   */
  hiddenIconName: false,
  /**
   * 图标阴影
   */
  iconShadow: true,
  /**
   * 图标动画
   */
  iconAnimation: true,
}

export const initialAppConfigState = {
  page,
  box,
  background,
  systemSettins,
  ...other,
}

export const appConfigSlice = createSlice({
  name: 'appConfig',
  initialState: initialAppConfigState,
  reducers: {
    /**
     * appConfig初始化
     * @param state initialAppConfigState
     * @param actions initialAppConfigState
     * @returns 
     */
    initAppConfig: (state, actions: PayloadAction<Partial<typeof initialAppConfigState>>) => {
      state = {
        ...initialAppConfigState,
        ...actions.payload
      }
      document.querySelector('body')?.setAttribute('theme', state.theme)
      appLocalStorage.setValue('appConfig', state)
      return state
    },
    reset: (state) => {
      document.querySelector('body')?.setAttribute('theme', initialAppConfigState.theme)
      state = initialAppConfigState
      appLocalStorage.setValue('appConfig', state)
      return state
    },
    // 更新背景设置
    updataBackground: (state, actions: PayloadAction<Partial<typeof state.background>>) => {
      const newData = {
        ...state.background,
        ...actions.payload
      }
      state.background = newData
      updateUserAppConfig(state)
    },
    /**
     * 更新系统设置
     */
    updataSystemSettings: (state, actions: PayloadAction<Partial<typeof state.systemSettins>>) => {
      const newData = {
        ...state.systemSettins,
        ...actions.payload
      }
      state.systemSettins = newData
      updateUserAppConfig(state)
    },
    // 更新盒子设置
    updataBox: (state, actions: PayloadAction<Partial<typeof state.box>>) => {
      const newData = {
        ...state.box,
        ...actions.payload
      }
      state.box = newData
      updateUserAppConfig(state)
    },
    // 更新页面设置
    updataPage: (state, actions: PayloadAction<Partial<typeof state.page>>) => {
      const newPageBoxs: any = {}

      let newData = {
        ...state.page,
        ...actions.payload
      }
      if (!isEmpty(actions.payload.pageList) || !isNil(actions.payload.pageList)) {
        actions.payload.pageList?.forEach(element => {
          const findIndex = Object.keys(state.page.boxs).findIndex(e => e === element.key)

          if (findIndex !== -1) {
            newPageBoxs[element.key] = (state.page.boxs as any)[element.key]
          } else {
            newPageBoxs[element.key] = {
              list: []
            }
          }
        })
        newData = {
          ...newData,
          boxs: newPageBoxs
        }
      }
      if (isEmpty((newData.boxs as any)[newData.currentPage])) {
        newData.currentPage = newData.pageList[0].key
      }
      state.page = newData
      updateUserAppConfig(state)
    },
    updataPageBoxList: (state, actions: PayloadAction<Partial<typeof state.page.boxs>>) => {
      (state.page.boxs as any)[state.page.currentPage].list = actions.payload as any
      updateUserAppConfig(state)
    },
    // 更新设置
    update: (state, actions: PayloadAction<{
      fieldName: keyof OtherType,
      value: OtherType[keyof OtherType]
    }>) => {
      const {
        fieldName,
        value
      } = actions.payload;
      (state[fieldName] as any) = value;

      updateUserAppConfig(state);
      return state
    },
    // 更新其他设置
    updateOther: (state, actions: PayloadAction<Partial<OtherType>>) => {
      state = {
        ...state,
        ...actions.payload
      }
      updateUserAppConfig(state);
      return state
    },
    // 添加图标
    addWebsitePart: (state, actions: PayloadAction<WebsitePartType>) => {
      let newBoxs = state.page.boxs as any
      if (isEmpty(newBoxs[state.page.currentPage])) {
        newBoxs = {
          ...newBoxs,
          [state.page.currentPage]: {
            list: [actions.payload]
          }
        }
      } else {
        newBoxs[state.page.currentPage].list.push(actions.payload)
      }
      state.page.boxs = newBoxs
      updateUserAppConfig(state)
    },
  },
})

export const appConfigActions = appConfigSlice.actions

export const appConfigReducer = appConfigSlice.reducer

export type AppConfigType = typeof initialAppConfigState

